import Koa from "koa";
import { logger } from "../log/log";
import { CODE } from "../config/code";
import { Context } from "koa";

/**
 * 响应处理中间件，格式化响应数据
 */
export const responseHandler = (ctx: Context) => {
  if (ctx.body !== undefined) {
    ctx.type = "json";
    if (ctx.body === null) {
      ctx.body = null;
    } else {
      ctx.body = {
        code: CODE.success.code,
        data: ctx.body,
        message: CODE.success.message,
      };
    }
  }
};

/**
 * 错误处理中间件，
 */
export const errorHandler = (ctx: Koa.Context, next: Koa.Next) => {
  return next().catch((err: { code: any; message: any }) => {
    if (typeof err === "object") {
      ctx.body = {
        code: err.code || -1,
        data: null,
        message: err.message,
      };
    } else {
      ctx.body = {
        code: -1,
        data: null,
        message: err,
      };
    }
    console.log(err)
    logger.error(err);

    // 保证返回状态是 200
    ctx.status = 200;
    return Promise.resolve();
  });
};